package com.bookyourtrek.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author ananda
 * generate md5 hash
 * @return md5 encoded string
 */
public class UtilityFunctions {
	
	public static String generateMD5(String inputtext) {
		//securing password
		//md5 hashing begins here
		MessageDigest mdAlgorithm = null;
		try {
			mdAlgorithm = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		mdAlgorithm.update(inputtext.getBytes());

		byte[] digest = mdAlgorithm.digest();
		StringBuffer hexString = new StringBuffer();

		for (int i = 0; i < digest.length; i++) {
			inputtext = Integer.toHexString(0xFF & digest[i]);

		    if (inputtext.length() < 2) {
		    	inputtext = "0" + inputtext;
		    }

		    hexString.append(inputtext);
		}
		//System.out.println((hexString.toString()));
		return hexString.toString();
		//md5 hashing ends here
	}
	
	
	/**
	 * @author ananda
	 * Generates unique string
	 * @return random string
	 */
	public static String randomStringGenerator() {
		UUID randomkey = UUID.randomUUID();
		return randomkey.toString();
	}
	
	/**
	 * @author ananda
	 * function to check whether a string is nuemeric or not
	 * @param str
	 * @return boolean
	 */
	public static boolean isNumeric(String str)
	{
	  return str.matches("-?\\d+(\\.\\d+)?");  //match a number with optional '-' and decimal.
	}

	/**
	 * @author ananda
	 * function to create random URL
	 * @return random string
	 */
	public static String createRandomUrl() {
		UUID randomkey = UUID.randomUUID();
		return randomkey.toString();
	}
	
	/**
	 * function to validate email address
	 * @param hex
	 * @return true/false
	 */
	public static boolean validateEmail(final String hex) {
		Pattern pattern = null;
		Matcher matcher;
		String EMAIL_PATTERN = 
				"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
				+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		pattern = Pattern.compile(EMAIL_PATTERN);
		matcher = pattern.matcher(hex);
		return matcher.matches();
 
	}
}
